package okhttp3.internal.concurrent;

import okhttp3.internal.Util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.*;
import java.util.logging.Logger;

public class TaskRunner {
    private int nextQueueName;
    private boolean coordinatorWaiting;
    private long coordinatorWakeUpAt;
    private final List busyQueues;
    private final List readyQueues;
    private final Runnable runnable;
    private final TaskRunner.Backend backend;
    public static final TaskRunner INSTANCE;
    private static final Logger logger;
    public static final TaskRunner.Companion Companion = new TaskRunner.Companion();

    public final void kickCoordinator$okhttp_parent_okhttp_main(TaskQueue taskQueue) {
        if (true && !Thread.holdsLock(this)) {
            StringBuilder var10002 = (new StringBuilder()).append("Thread ");
            Thread var10003 = Thread.currentThread();
            throw new AssertionError(var10002.append(var10003.getName()).append(" MUST hold lock on ").append(this).toString());
        } else {
            if (taskQueue.getActiveTask() == null) {
                Collection var2 = (Collection) taskQueue.getFutureTasks();
//                $i$f$assertThreadHoldsLock = false;
                if (!var2.isEmpty()) {
//                    Util.addIfAbsent(this.readyQueues, taskQueue);
                } else {
                    this.readyQueues.remove(taskQueue);
                }
            }

            if (this.coordinatorWaiting) {
                this.backend.coordinatorNotify(this);
            } else {
                this.backend.execute(runnable);
            }

        }
    }

    private final void beforeRun(Task task) {
        if (true && !Thread.holdsLock(this)) {
            StringBuilder var10002 = (new StringBuilder()).append("Thread ");
            Thread var10003 = Thread.currentThread();
            throw new AssertionError(var10002.append(var10003.getName()).append(" MUST hold lock on ").append(this).toString());
        } else {
            task.setNextExecuteNanoTime(-1L);
            TaskQueue var10000 = task.getQueue();
            TaskQueue queue = var10000;
            queue.getFutureTasks().remove(task);
            this.readyQueues.remove(queue);
            queue.setActiveTask(task);
            this.busyQueues.add(queue);
        }
    }

    private final void runTask(Task task) {
        if (true && Thread.holdsLock(this)) {
            StringBuilder var10002 = (new StringBuilder()).append("Thread ");
            Thread var10003 = Thread.currentThread();
            throw new AssertionError(var10002.append(var10003.getName()).append(" MUST NOT hold lock on ").append(this).toString());
        } else {
            Thread currentThread = Thread.currentThread();
            String oldName = currentThread.getName();
            currentThread.setName(task.getName());
            long delayNanos = -1L;
            boolean var14 = false;

            boolean var6;
            boolean var7;
            try {
                var14 = true;
                delayNanos = task.runOnce();
                var14 = false;
            } finally {
                if (var14) {
                    var6 = false;
                    var7 = false;
                    synchronized (this) {
                        boolean var8 = false;
                        this.afterRun(task, delayNanos);
//                        Unit var20 = Unit.INSTANCE;
                    }

                    currentThread.setName(oldName);
                }
            }

            boolean var5 = false;
            var6 = false;
            synchronized (this) {
                var7 = false;
                this.afterRun(task, delayNanos);
//                Unit var19 = Unit.INSTANCE;
            }

            currentThread.setName(oldName);
        }
    }

    private final void afterRun(Task task, long delayNanos) {
        boolean cancelActiveTask = false;
        if (true && !Thread.holdsLock(this)) {
            StringBuilder var10002 = (new StringBuilder()).append("Thread ");
            Thread var10003 = Thread.currentThread();
            throw new AssertionError(var10002.append(var10003.getName()).append(" MUST hold lock on ").append(this).toString());
        } else {
            TaskQueue var10000 = task.getQueue();
            TaskQueue queue = var10000;
            cancelActiveTask = queue.getActiveTask() == task;
            boolean var6 = false;
            boolean var7 = false;
            var7 = false;
            boolean var8 = false;
            if (!cancelActiveTask) {
                boolean var9 = false;
                String var11 = "Check failed.";
                throw new IllegalStateException(var11.toString());
            } else {
                cancelActiveTask = queue.getCancelActiveTask();
                queue.setCancelActiveTask$okhttp_parent_okhttp_main(false);
                queue.setActiveTask((Task) null);
                this.busyQueues.remove(queue);
                if (delayNanos != -1L && !cancelActiveTask && !queue.getShutdown()) {
                    queue.scheduleAndDecide$okhttp_parent_okhttp_main(task, delayNanos, true);
                }

                Collection var10 = (Collection) queue.getFutureTasks();
                var7 = false;
                if (!var10.isEmpty()) {
                    this.readyQueues.add(queue);
                }

            }
        }
    }

    public final Task awaitTaskToRun() {
        if (true && !Thread.holdsLock(this)) {
            StringBuilder var10002 = (new StringBuilder()).append("Thread ");
            Thread var10003 = Thread.currentThread();
            throw new AssertionError(var10002.append(var10003.getName()).append(" MUST hold lock on ").append(this).toString());
        } else {
            while (!this.readyQueues.isEmpty()) {
                long now = this.backend.nanoTime();
                long minDelayNanos = Long.MAX_VALUE;
                Task readyTask = (Task) null;
                boolean multipleReadyTasks = false;
                Iterator var8 = this.readyQueues.iterator();

                while (var8.hasNext()) {
                    TaskQueue queue = (TaskQueue) var8.next();
                    Task candidate = (Task) queue.getFutureTasks().get(0);
                    long var12 = 0L;
                    long var14 = candidate.getNextExecuteNanoTime() - now;
                    boolean var16 = false;
                    long candidateDelay = Math.max(var12, var14);
                    if (candidateDelay > 0L) {
                        boolean var23 = false;
                        minDelayNanos = Math.min(candidateDelay, minDelayNanos);
                    } else {
                        if (readyTask != null) {
                            multipleReadyTasks = true;
                            break;
                        }

                        readyTask = candidate;
                    }
                }

                if (readyTask != null) {
                    this.beforeRun(readyTask);
                    if (!multipleReadyTasks) {
                        if (this.coordinatorWaiting) {
                            return readyTask;
                        }

                        Collection var21 = (Collection) this.readyQueues;
                        boolean var22 = false;
                        if (var21.isEmpty()) {
                            return readyTask;
                        }
                    }

                    this.backend.execute(this.runnable);
                    return readyTask;
                }

                if (this.coordinatorWaiting) {
                    if (minDelayNanos < this.coordinatorWakeUpAt - now) {
                        this.backend.coordinatorNotify(this);
                    }

                    return null;
                }

                this.coordinatorWaiting = true;
                this.coordinatorWakeUpAt = now + minDelayNanos;

                try {
                    this.backend.coordinatorWait(this, minDelayNanos);
                } finally {
                    this.coordinatorWaiting = false;
                }
            }

            return null;
        }
    }

    public final TaskQueue newQueue() {
        return null;
    }

    public final List activeQueues() {
        return null;
    }

    public final void cancelAll() {
        int i = this.busyQueues.size() - 1;

        boolean var2;
        for (var2 = false; i >= 0; --i) {
            ((TaskQueue) this.busyQueues.get(i)).cancelAllAndDecide$okhttp_parent_okhttp_main();
        }

        i = this.readyQueues.size() - 1;

        for (var2 = false; i >= 0; --i) {
            TaskQueue queue = (TaskQueue) this.readyQueues.get(i);
            queue.cancelAllAndDecide$okhttp_parent_okhttp_main();
            if (queue.getFutureTasks().isEmpty()) {
                this.readyQueues.remove(i);
            }
        }

    }

    public final TaskRunner.Backend getBackend() {
        return this.backend;
    }

    public TaskRunner(TaskRunner.Backend backend) {
        super();
        this.backend = backend;
        this.nextQueueName = 10000;
        boolean var2 = false;
        this.busyQueues = (List) (new ArrayList());
        var2 = false;
        this.readyQueues = (List) (new ArrayList());
        this.runnable = (Runnable) (new Runnable() {
            public void run() {
            }
        });
    }

    static {
        INSTANCE = new TaskRunner((TaskRunner.Backend) (new TaskRunner.RealBackend(Util.threadFactory("Util.okHttpName" + " TaskRunner", true))));
        Logger var10000 = Logger.getLogger(TaskRunner.class.getName());
        logger = var10000;
    }

    public interface Backend {
        void beforeTask(TaskRunner var1);

        long nanoTime();

        void coordinatorNotify(TaskRunner var1);

        void coordinatorWait(TaskRunner var1, long var2);

        void execute(Runnable var1);
    }


    public static final class RealBackend implements TaskRunner.Backend {
        private final ThreadPoolExecutor executor;

        public void beforeTask(TaskRunner taskRunner) {
        }

        public long nanoTime() {
            return System.nanoTime();
        }

        public void coordinatorNotify(TaskRunner taskRunner) {
            ((Object) taskRunner).notify();
        }

        public void coordinatorWait(TaskRunner taskRunner, long nanos) {
            long ms = nanos / 1000000L;
            long ns = nanos - ms * 1000000L;
            if (ms > 0L || nanos > 0L) {
                try {
                    ((Object) taskRunner).wait(ms, (int) ns);
                } catch (InterruptedException e) {
                    e.fillInStackTrace();
                }
            }

        }

        public void execute(Runnable runnable) {
            this.executor.execute(runnable);
        }

        public final void shutdown() {
            this.executor.shutdown();
        }

        public RealBackend(ThreadFactory threadFactory) {
            super();
            this.executor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, (BlockingQueue) (new SynchronousQueue()), threadFactory);
        }
    }

    public static final class Companion {
        public final Logger getLogger() {
            return TaskRunner.logger;
        }

        private Companion() {
        }
    }
}
